package sms

import (
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/pkg/constant"
)

type TencentSmsService struct {
	SecretId   string //腾讯云API密钥Id
	SecretKey  string //腾讯云API密钥
	Method     string //接入域名
	SignName   string //短信签名
	SdkAppId   string //短信应用的appId
	TemplateId string //短信模板id
}

func NewTencentSmsService() (*TencentSmsService, error) {
	return &TencentSmsService{
		SecretId:   constant.TencentSecretId,
		SecretKey:  constant.TencentSecretKey,
		Method:     constant.TencentMethod,
		SignName:   constant.TencentSmsSignName,
		SdkAppId:   constant.TencentSmsSdkAppId,
		TemplateId: constant.TencentSmsTemplateId,
	}, nil
}

// Send -发送腾讯云短信
func (s *TencentSmsService) Send(phone, code string) error {
	credential := common.NewCredential(s.SecretId, s.SecretKey)
	cpf := profile.NewClientProfile()

	cpf.HttpProfile.Endpoint = s.Method

	client, _ := sms.NewClient(credential, regions.Guangzhou, cpf)
	request := sms.NewSendSmsRequest()

	/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
	// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
	request.SmsSdkAppId = common.StringPtr(s.SdkAppId)

	/* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
	// 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
	request.SignName = common.StringPtr(s.SignName)

	/* 模板 ID: 必须填写已审核通过的模板 ID */
	// 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
	request.TemplateId = common.StringPtr(s.TemplateId)

	/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空*/
	request.TemplateParamSet = common.StringPtrs([]string{code, constant.SmsExpire})
	request.PhoneNumberSet = common.StringPtrs([]string{phone})

	// 通过client对象调用想要访问的接口，需要传入请求对象
	_, err := client.SendSms(request)
	if err != nil {
		logx.Errorf("发送短信失败%v", err)
		return err
	}
	return nil
}
